package com.funo.main.ctrler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.funo.common.factory.JsonMsgFactory;
import com.funo.common.pojo.PageResult;
import com.funo.common.pojo.QueryCondition;
import com.funo.common.pojo.TreeNode;
import com.funo.common.tools.ResponseTool;
import com.funo.common.utils.Constant;
import com.funo.core.base.BaseCtrler;
import com.funo.core.base.BaseException;
import com.funo.main.entities.User;
import com.funo.main.entities.UserRole;
import com.funo.main.service.RoleService;
import com.funo.main.service.UserService;

/**
 * 用户模块业务处理实现类
 * 
 * @author wengx,zhengjs
 *
 */
@SuppressWarnings({"unchecked","unused"})
@Controller
@RequestMapping("/user")
public class UserCtrler extends BaseCtrler{
	@Autowired
	private UserService userService;//用户service

	@Autowired
	private RoleService roleService;//角色service
	
	/**
	 * 用户登录
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "/login";
	}
	
	@RequestMapping(value="/logout" ,method = RequestMethod.POST)
	public String logout(HttpServletRequest request){
		request.getSession(false).invalidate();
		return "/login";
	}

	/**
	 * 用户登录
	 * 
	 * @param userVO
	 *            用户表
	 * @return
	 */
	@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
	@ResponseBody
	public  String login(HttpSession session, HttpServletRequest request,HttpServletResponse response, User userVO) {
		try {
			User user = userService.login(userVO);
			
			if (user != null) {// 用户存在
				session.setAttribute("user", user);
//				ResponseTool.responseJson(JsonMsgFactory.successMsg(), request, response);
//				return null;
				return toJson(JsonMsgFactory.successMsg());
			} else {
//				ResponseTool.responseJson(JsonMsgFactory.fail("用户名或密码错误,请重新输入!"), request, response);
//				return null;
				return toJson(JsonMsgFactory.loginErrorMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
//			ResponseTool.responseJson(JsonMsgFactory.fail("用户名或密码错误,请重新输入!"), request, response);
//			return null;
			return toJson(JsonMsgFactory.failMsg());
		}
	}

	/**
	 * 跳转到系统主界面
	 * 
	 * @return
	 */
	@RequestMapping(value="/index")
	public String index() {
		return "/index";
	}

	/**
	 * 新增用户操作
	 * 
	 * @param session session会话
	 * @param user 用户表
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public @ResponseBody String add(HttpSession session,User user) {
		
		if(sessionUser(session) == null || sessionUser(session).getId() == null){//丢失session
			return toJson(JsonMsgFactory.fail("请先登录,再进行操作!"));
		}
		
		if (user != null) {//用户不为空
			
			try {				
				
				Integer type=userService.saveUser(sessionUser(session),user);
				
				if (type == Constant.STATUS_SUSSESS) {//成功
					return toJson(JsonMsgFactory.successMsg());
				}
				
				if (type == Constant.STATUS_REPEAT) {//重复添加
					return toJson(JsonMsgFactory.fail("请勿重复添加,添加失败"));
				}
			} catch (Exception e) {//失败
				e.printStackTrace();
				return toJson(JsonMsgFactory.failMsg());
			}
		}
		
		return null;
	}

	/**
	 * 修改用户操作
	 * 
	 * @param session session会话
	 * @param user 用户表
	 * @return
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public @ResponseBody String edit(HttpSession session,User user) {
		
		if(sessionUser(session) ==null || sessionUser(session).getId() == null){//丢失session
			return toJson(JsonMsgFactory.fail("请先登录,再进行操作!"));
		}
		
		try {

			Integer type = userService.updateUser(sessionUser(session),user);//修改操作
			
			if (type == Constant.STATUS_SUSSESS) {
				return toJson(JsonMsgFactory.successMsg());
			}
			
			if (type == Constant.STATUS_REPEAT) {
				return toJson(JsonMsgFactory.fail("修改的信息已存在，修改失败"));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return toJson(JsonMsgFactory.failMsg());
		}
		
		return null;
	}

	/**
	 * 删除操作
	 * 
	 * @param deleteIds id集合 
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody String delete(String deleteIds){
		
		try {

			String[]Ids=deleteIds.split(",");//传递到数据库的参数

			for (int i = 0; i < Ids.length; i++) {
				
				String id=Ids[i];
				
				User user=userService.getUser(id);//用户信息
				
				userService.deleteUser(user);//删除用户
			}

			return toJson(JsonMsgFactory.successMsg());
			
		} catch (Exception e) {
			return toJson(JsonMsgFactory.failMsg());
		}
	}

	/**
	 * 用户角色信息
	 * 
	 * @param id 用户id
	 * @return
	 */
	@RequestMapping(value = "/userRole")
	public @ResponseBody String userRole(String id) {
		TreeNode root = roleService.userRoleTree(id);
		return toJson(root);
	}
	
	/**
	 * 查看已经选择的角色信息
	 * 
	 * @param userRole 用户角色表
	 * @param checked 是否已经选择,true已经选择,false未选择
	 * @return
	 */
	@RequestMapping(value = "/check")
	public @ResponseBody String check(UserRole userRole,@RequestParam(value="checked")boolean checked){
		try {
			roleService.checkUserRole(userRole, checked);
			return toJson(JsonMsgFactory.successMsg());
		} catch (Exception e) {
			e.printStackTrace();
			return toJson(JsonMsgFactory.failMsg());
		}
	}
	
	@RequestMapping(value = "/get")
	public String get(String id) {
		User user = userService.getUser(id);
		return "/login";
	}
	
	/**
	 * 查询所有用户信息
	 * 
	 * @param condition 查询条件集合
	 * @return
	 */
	@RequestMapping(value = "/page",method=RequestMethod.GET)
	//@ResponseBody
	public  String page(QueryCondition condition,HttpServletRequest request,HttpServletResponse response) {
		PageResult<User> page = userService.getUserPage(condition);
		ResponseTool.responseJson(page, request, response);
		return null;
	}

	@Override
	protected String handlerException(Exception e) {
		e.printStackTrace();
		System.err.println("[handlerException:MemberController]异常类型："+e.getClass().getSimpleName());
		System.err.println(e.getMessage());
		return "系统异常";
	}

}
